<template>
  <div class="other-setting-panel">
    <!--S 公共设置 -->
    <div class="other-setting-main mb-12">
      <div>
        <h2 style="margin-top: 0">
          {{$t('task.setting.taskTypeSetting.flow.tabs.title4')}}
          <el-switch
            class="ml-12"
            v-model="taskFlowData.taskTypeConfig.planRemindSetting.state"
          />
        </h2>
        <div class="mb-8" v-show="taskFlowData.taskTypeConfig.planRemindSetting.state">
          {{$t('task.edit.at')}}
          <el-select
            class="w-120"
            v-model="taskFlowData.taskTypeConfig.planRemindSetting.planTimeType"
            :placeholder="$t('common.placeholder.select')"
            v-if="isCalendar"
          >
            <el-option
              v-for="item in optionsSelect"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
          <span v-else>{{$t('common.form.type.planTime')}}</span>
          <el-select
            class="w-104"
            v-model="taskFlowData.taskTypeConfig.planRemindSetting.minutesType"
            :placeholder="$t('common.placeholder.select')"
          >
            <el-option :label="$t('common.base.before')" :value="0"> </el-option>
            <el-option :label="$t('common.base.after')" :value="1"> </el-option>
          </el-select>
          <el-input
            class="w-104"
            onkeyup="this.value=this.value.replace(/\D/g,'')"
            v-model="taskFlowData.taskTypeConfig.planRemindSetting.minutes"
          />
          {{$t('task.setting.taskTypeSetting.flow.tabs.title5')}}
          <el-select v-model="taskFlowData.taskTypeConfig.noticeLeader" :placeholder="$t('common.placeholder.select')">
            <el-option
              v-for="item in planOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <div v-if="taskFlowData.taskTypeConfig.noticeLeader == 2">
            <el-input
              v-if="!isOpenData"
              class="w-678 mt-8"
              :placeholder="$t('task.setting.taskTypeSetting.flow.components.placeholder1')"
              readonly
              :value="getApproverNames(taskFlowData.taskTypeConfig.noticeUsers)"
              @click.native="selectApproveUser('planRemind')"
            />
            <div v-else class="setting-open-data-input w-678 mt-8" @click="selectApproveUser('planRemind')">
              <template v-if="!taskFlowData.taskTypeConfig.noticeUsers || !taskFlowData.taskTypeConfig.noticeUsers.length"><span class="placeholder-text">{{$t('task.setting.taskTypeSetting.flow.components.placeholder1')}}</span></template>
              <template v-else v-for="(item, index) in getApproverIds(taskFlowData.taskTypeConfig.noticeUsers)">
                <open-data :key="item" type="userName" :openid="item"></open-data>
                <ui-separator :index="index" :list="getApproverIds(taskFlowData.taskTypeConfig.noticeUsers)" :key="`${item}${uuid()}`" />
              </template>
              <!-- <open-data v-for="staffId in getApproverIds(taskFlowData.taskTypeConfig.noticeUsers)" :key="staffId" type="userName" :openid="staffId"></open-data> -->
            </div>
          </div>
        </div>
        <div v-if="showTips" class="show-tips">{{$t('task.setting.taskTypeSetting.flow.tabs.tip3')}}</div>
      </div>
      <div class="setting-specific-form">
        <h2>
          {{$t('task.setting.taskTypeSetting.flow.tabs.title6')}}
          <el-switch class="ml-12" v-model="taskFlowData.taskTypeConfig.allowPause" />
        </h2>
        <approve-setting
          v-show="taskFlowData.taskTypeConfig.allowPause"
          :options="options.pause"
          flowType="pause"
          :task-type-id="taskTypeId" 
          :optionMaps="optionMaps"
          :isFromAdvanced="true"
          :approve-setting="taskFlowData.taskTypeConfig.pauseApproveSetting"
          @change="(setting) => changeApproveSetting(setting, 'pause')"
        />
      </div>
      <div class="setting-specific-form">
        <h2>
          {{$t('task.setting.taskTypeSetting.flow.tabs.title7')}}
          <el-tooltip
            placement="top"
            :content="$t('task.setting.taskTypeSetting.flow.tabs.tip4')">
            <i class="el-icon-question el-tooltip"></i>
          </el-tooltip>
          <el-switch class="ml-12" v-model="taskFlowData.taskTypeConfig.allowCancel" />
        </h2>
        <approve-setting
          v-show="taskFlowData.taskTypeConfig.allowCancel"
          :options="options.cancel"
          :isFromAdvanced="true"
          flowType="off"
          :task-type-id="taskTypeId" 
          :optionMaps="optionMaps"
          :approve-setting="taskFlowData.taskTypeConfig.cancelApproveSetting"
          @change="(setting) => changeApproveSetting(setting, 'cancel')"
        />
      </div>
    </div>
    <!--E 公共设置 -->

    <div class="other-setting-main mt-12 mb-12" v-if="triggerGray">
      <!--S 触发器 -->
      <trigger-list-setting
        :subTitle="$t('common.connector.trigger.taskSubTitle')" 
        bizType="TASK"
        :bizTypeId="taskFlowData.taskTypeId"
      >
      </trigger-list-setting>
      <!--E 触发器 -->
    </div>

    <!--S 生成服务报告 -->
    <div v-if="isShowTaskServiceReport" class="setting-service-report other-setting-main mb-12">
      <div>
        <div class="setting-service-report-title">
          <div class="setting-service-report-title__left">
            <h2 style="margin-top: 0px;">
              {{$t('task.setting.taskTypeSetting.flow.tabs.title8')}}
              <span>{{$t('task.setting.taskTypeSetting.flow.tabs.title9')}}</span>
            </h2>
            <span class="desc">
              {{$t('task.setting.taskTypeSetting.flow.tabs.title10')}}
              <el-popover
                placement="bottom-end"
                title=""
                width="200"
                trigger="manual"
                v-model="srPopoverVisible"
                popper-class="sr-popover">
                <div class="sr-popover-content">
                  <h3>{{$t('task.setting.taskTypeSetting.flow.tabs.title11')}}</h3>
                  <span>{{$t('task.setting.taskTypeSetting.flow.tabs.title12')}}</span>
                  <el-button type="primary" size="small" @click="openServiceReportIntroDialog">{{$t('task.setting.taskTypeSetting.flow.tabs.learnMore')}}</el-button>
                  <i class="el-icon-close" @click="srNewNoticeVisible = false"></i>
                </div>
                <el-button slot="reference" type="text" @click="openServiceReportIntroDialog">{{$t('task.setting.taskTypeSetting.flow.tabs.learnMore')}}</el-button>
              </el-popover>
            </span>
          </div>
          <div class="setting-service-report-title__right">
            <el-button v-if="taskFlowData.taskTypeConfig.options.serviceReport" type='primary' @click="serviceReportClickHandler('create')">{{$t('common.base.createRuler')}}</el-button>
            <el-switch class="ml-16" v-model="taskFlowData.taskTypeConfig.options.serviceReport"/>
          </div>
        </div>
        <div class="mt-12" v-if="taskFlowData.taskTypeConfig.options.serviceReport">
          <div class="service-report-box">
            <div v-for="item in serviceReportList" :key="item.id" class="service-report-item">
              <div class="service-report-item__left">
                {{ getForeignName(item.foreignName) }}
              </div>
              <div class="service-report-item__right">
                <div class="service-report-item-content">
                  <div class="mar-b-8">{{$t('task.setting.taskTypeSetting.flow.components.serviceReportTitle31')}}:
                    <span>{{ getStateName(item.taskStatus) || '' }}</span>
                  </div>
                  <div class="mar-b-8">{{$t('task.setting.taskTypeSetting.flow.tabs.title13')}}:
                    <span>{{ item.templateType === 2 ? $t('task.setting.taskTypeSetting.flow.tabs.title14') : $t('task.setting.taskTypeSetting.flow.tabs.title15') }}</span>
                  </div>
                  <div>{{$t('task.setting.taskTypeSetting.flow.components.serviceReportTitle35')}}:
                    <span>{{ item.needSign === 0 ? $t('common.base.notNeed') : $t('common.base.need') }}</span>
                  </div>
                </div>
                <div class="service-report-item-opt-btn">
                  <el-button type='text' @click="serviceReportClickHandler('edit', item)">{{$t('common.base.edit')}}</el-button>
                  <el-button v-if="item.taskStatus !== 'finished'" type='text' @click="serviceReportClickHandler('delete', item)" class="red">{{$t('common.base.delete')}}</el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="setting-service-report-title" v-if="taskFlowData.taskTypeConfig.options.serviceReport">
          <div class="setting-service-report-title__left">
            <h2 style="margin: 0px;">{{ $t('task.setting.taskTypeSetting.flow.components.serviceReportTitle41') }}</h2>
          </div>
          <div class="setting-service-report-title__right">
            <el-switch v-model="taskFlowData.taskTypeConfig.options.isFinishNodeShowAllServiceReport" />
          </div>
        </div>
      </div>
    </div>
    <!--E 生成服务报告 -->
    
    <!--S 回执设置 -->
    <div class="other-setting-main mb-12">
      <!--S 工单费用折扣 -->
      <div class="setting-service-price" v-if="!isBasicEditionHidePay">
        <h2 style="margin-top: 0">
          {{$t('task.setting.taskTypeSetting.flow.tabs.title16')}}
          <span>{{$t('task.setting.taskTypeSetting.flow.tabs.title17')}}</span>
        </h2>
        <div class="mt-12">
          <el-checkbox v-model="taskFlowData.taskTypeConfig.options.editUnitPrice">{{$t('task.setting.taskTypeSetting.flow.tabs.title18')}}</el-checkbox>
          <el-checkbox v-model="taskFlowData.taskTypeConfig.options.showDiscountCost">{{$t('task.setting.taskTypeSetting.flow.tabs.title19')}}</el-checkbox>
        </div>
      </div>
      <!--E 工单费用折扣 -->

      <!--S 启用打印功能 -->
      <div class="setting-photo" v-if="!isBasicEditionHidePrintTask">
        <h2 :style="{ marginTop: (isBasicEditionHideServiceReport && isBasicEditionHidePay ? 0 : '36px') }">
          {{$t('task.setting.taskTypeSetting.flow.tabs.title20')}}
          <el-switch class="ml-16" v-model="taskFlowData.taskTypeConfig.options.printTask"/>
          <span>{{$t('task.setting.taskTypeSetting.flow.tabs.title21')}}</span>
        </h2>
        <div class="mt-12" v-show="taskFlowData.taskTypeConfig.options.printTask">
          <el-radio-group v-model="taskFlowData.taskTypeConfig.options.ptSysTemplate">
            <el-radio :label="true" class="mr-50">
              <span>{{$t('task.setting.taskTypeSetting.flow.tabs.title15')}}</span>
              <el-button
                :disabled="!taskFlowData.taskTypeConfig.options.ptSysTemplate"
                :type="taskFlowData.taskTypeConfig.options.ptSysTemplate ? 'primary': 'default'" 
                plain 
                size="small"
                @click="openTemplateDialog('printSetting')">
                {{$t('common.base.setting')}}
              </el-button>
            </el-radio>
            <el-radio :label="false">
              {{$t('task.setting.taskTypeSetting.flow.tabs.title22')}}
              <el-button
                :disabled="taskFlowData.taskTypeConfig.options.ptSysTemplate"
                :type="!taskFlowData.taskTypeConfig.options.ptSysTemplate ? 'primary': 'default'" 
                plain 
                @click="importPresonTemplate('printSetting')"
                size="small">
                {{$t('common.base.setting')}}
              </el-button>
            </el-radio>
          </el-radio-group>
        </div>
                
      </div>
      <!--E 启用打印功能 -->

      <!--S 启用拍照设置 -->
      <div class="setting-photo">
        <h2 :style="{ marginTop: (isBasicEditionHideServiceReport && isBasicEditionHidePrintTask && isBasicEditionHidePay ? 0 : '36px') }">
          {{$t('task.setting.taskTypeSetting.flow.tabs.title23')}}
          <el-switch
            class="ml-16"
            v-model="taskFlowData.taskTypeConfig.config.positionExceptionConfig.attUploadLimitMobile"/>
        </h2>
        {{$t('task.setting.taskTypeSetting.flow.tabs.title24')}}
      </div>
      <!--E 启用拍照设置 -->

      <!--S 照片水印设置 -->
      <div class="setting-water-mark" v-if="taskFlowData.taskTypeConfig.config.positionExceptionConfig.attUploadLimitMobile">
        <h2>
          {{$t('task.setting.taskTypeSetting.flow.tabs.title25')}}
          <el-switch class="ml-16" v-model="taskFlowData.taskTypeConfig.config.positionExceptionConfig.photoWatermark"/>
        </h2>
        <div v-show="taskFlowData.taskTypeConfig.config.positionExceptionConfig.photoWatermark">
        <i18n path="task.setting.taskTypeSetting.flow.tabs.title26">
          <el-select
            place="position"
            v-model="taskFlowData.taskTypeConfig.config.positionExceptionConfig.watermarkPosition"
            :placeholder="$t('task.setting.taskTypeSetting.flow.tabs.placeholder1')">
            <el-option
              v-for="item in waterMarkDirection"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </i18n>
        </div>
        <div class="mt-8" v-show="taskFlowData.taskTypeConfig.config.positionExceptionConfig.photoWatermark">
          <el-select class="w-542" v-model="taskFlowData.taskTypeConfig.config.positionExceptionConfig.watermarkContent" multiple :placeholder="$t('task.setting.taskTypeSetting.flow.tabs.placeholder1')">
            <el-option
              v-for="item in photoInfoArr"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </div>
      </div>
      <!--E 照片水印设置 -->

      <!--S 位置异常设置 -->
      <div class="setting-postion-exception">
        <h2>
          {{$t('task.setting.taskAdditionalSetting.positionExceptionRemind')}}
          <el-switch class="ml-16" v-model="taskFlowData.taskTypeConfig.config.positionExceptionConfig.positionExceptionFlag" />
        </h2>
        <p style="color: #999999" v-show="taskFlowData.taskTypeConfig.config.positionExceptionConfig.positionExceptionFlag">
          <i18n path="task.setting.taskTypeSetting.flow.tabs.title27">
            <el-input place="km" class="w-120" v-model="taskFlowData.taskTypeConfig.config.positionExceptionConfig.exceptionRange" onkeyup="if(isNaN(value))execCommand('undo')" :placeholder="$t('task.setting.taskTypeSetting.flow.tabs.placeholder1')"></el-input>
          </i18n>
        </p>
        <div v-show="taskFlowData.taskTypeConfig.config.positionExceptionConfig.positionExceptionFlag">{{$t('task.setting.taskTypeSetting.flow.tabs.title28')}}</div>
        <div class="mt-12" v-show="taskFlowData.taskTypeConfig.config.positionExceptionConfig.positionExceptionFlag">
          <el-select class="w-542" v-model="taskFlowData.taskTypeConfig.config.positionExceptionConfig.exceptionFlagFlows" multiple :placeholder="$t('common.placeholder.select')">
            <el-option
              v-for="item in processArr"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </div>
      </div>
      <!--E 位置异常设置 -->

      <!--S 工单流程完成时间取审批完成时间 -->
      <div class="setting-postion-exception">
        <h2>
          {{$t('task.setting.taskTypeSetting.flow.tabs.title43')}}
          <el-switch class="ml-16" v-model="taskFlowData.taskTypeConfig.config.changeCompleteFlag" />
        </h2>
        <p style="color: #999999">{{$t('task.setting.taskTypeSetting.flow.tabs.title44')}}</p>
        <div class="mt-12" v-show="taskFlowData.taskTypeConfig.config.changeCompleteFlag">
          <el-select class="w-542" v-model="taskFlowData.taskTypeConfig.config.changeCompleteNode" multiple :placeholder="$t('common.placeholder.select')">
            <el-option
              v-for="item in taskProcessNodeArr"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </div>
      </div>
      <!--E 工单流程完成时间取审批完成时间 -->

      <!--S 知识库关联字段配置 -->
      <!-- 基础版没有知识库，是基础版的话就隐藏掉 -->
      <div class="setting-postion-exception" v-if="!isBasicEdition">
        <h2>
          {{$t('task.setting.taskTypeSetting.flow.tabs.title29')}}
          <el-tooltip
            placement="top"
            :content="$t('task.setting.taskTypeSetting.flow.tabs.tip5')">
            <i class="el-icon-question el-tooltip"></i>
          </el-tooltip>
        </h2>
        <div class="mt-12">
          <el-select
            class="w-542"
            v-model="wikiSettingIds"
            multiple
            :placeholder="$t('common.placeholder.select')">
            <el-option
              v-for="item in fieldTypeList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </div>
      </div>
      <!--E 知识库关联字段配置 -->

      <!--S 启用备件更换 -->
      <div class="setting-postion-exception" v-if="showReplaceProductCard">
        <h2>
          {{$t('task.setting.taskTypeSetting.flow.tabs.title30')}}
          <el-switch class="ml-16" v-model="taskFlowData.taskTypeConfig.options.replaceProductCard"/>
        </h2>
      </div>
      <!--E 启用备件更换 -->
    </div>
    <!--E 回执设置 -->

    <!-- S 智能质检设置 -->

    <!-- E 智能质检设置 -->

    <!-- 系统模板设置字段弹窗 -->
    <system-template-dialog 
      :visiable.sync="isShowSystemModal" 
      :type="templateType" 
      :task-type-id="taskFlowData.taskTypeId" 
      :reportSetting="currentReportSetting"
      @reportSettingSave="reportSettingSave"
    />

    <!-- 导入模板设置弹窗 -->
    <template-upload-dialog 
      :visiable.sync="isShowTemplateUploadModal" 
      :type="templateType" 
      :task-type-id="taskFlowData.taskTypeId" 
      :reportSetting="currentReportSetting"
      @reportSettingSave="reportSettingSave"
    />

    <!-- 服务报告功能介绍弹窗 -->
    <function-intro-dialog ref="functionIntroDialogRef"></function-intro-dialog>

    <!-- 新建编辑服务报告弹窗 -->
    <service-report-edit-dialog 
      ref="serviceReportEditDialogRef" 
      :taskStatusOptions="srTaskStatusOptions" 
      :existTypeStatus="srListExistTypeStatus" 
      :task-type-id="taskFlowData.taskTypeId" 
      @success="handleServiceReportSuccess" 
      @openTemplateDialog="srOpenTemplateDialog"
      />

  </div>
</template>

<script>
import { isCalendar } from '@src/util/CalendarUtil';
import { isOpenData } from '@src/util/platform'
import _ from 'lodash';
// api
import * as SettingTaskApi from '@src/api/SettingTaskApi.js';
import * as TaskApi from '@src/api/TaskApi.ts';
import * as SettingApi from '@src/api/SettingApi.ts';
// util
import { convertDataToParams, logDataToParams } from '../util';
import { isStandardEdition, isExperienceEdition } from '@shb-lib/version';
import { getRootWindow } from '@src/util/dom'
// components
import ApproveSetting from '../components/ApproveSetting.vue';
import SystemTemplateDialog from '../components/SystemTemplateDialog';
import TemplateUploadDialog from '../components/TemplateUploadDialog';
import FunctionIntroDialog from '../components/ServiceReport/FunctionIntroDialog';
import ServiceReportEditDialog from '../components/ServiceReport/ServiceReportEditDialog';
import { isBasicEditionHideServiceReport, isBasicEditionHidePrintTask, isBasicEditionHidePay, isBasicEdition} from '@shb-lib/version'

import { BaseSelectUserModeEnum } from '@src/component/common/BaseSelectUser'
import TriggerListSetting from '@src/modules/connector/components/trigger-list-setting/index.vue'
import TaskStateEnum from '@model/enum/TaskStateEnum'
import i18n from '@src/locales'
/* mixin */
import { VersionControlTaskMixin } from '@src/mixins/versionControlMixin'

export default {
  name: 'other-setting-panel',
  mixins: [VersionControlTaskMixin],
  inject: ['taskFlowData'],
  props: {
    taskTypeId: {
      type: String,
      default: ''
    },
    isShowPlanStartTime: {
      type: Boolean,
      default: false
    },
    isShowPlanEndTime: {
      type: Boolean,
      default: false
    },
    // 智能质检配置项字段
    intelligenceData: {
      type: Object,
      default: () => ({})
    },
    isUpdate: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      showTips: false,
      isOpenData,
      isShowSystemModal : false,
      templateType: 'reportSetting', // 'reportSetting' or 'printSetting
      isShowUploadModal : false,
      isShowTemplateUploadModal: false,

      formList: [],
      receiptList: [],

      options: {
        pause: [],
        cancel: [],
        flow: []
      },

      planOptions: [
        {
          value: '0',
          label: i18n.t('event.setting.constant.over_time_remind_type_options.label1'),
        },
        {
          value: '1',
          label: i18n.t('event.setting.constant.over_time_remind_type_options.label2'),
        },
        {
          value: '2',
          label: i18n.t('event.setting.constant.over_time_remind_type_options.label3'),
        },
      ],
      isCalendar, // 日历功能权限
      fieldTypeList: [],
      wikiSettingIds: this.taskFlowData?.initTaskTypeConfig?.config?.wikiSetting?.map(v => v.id) || [],
      srTaskStatusOptions: [],
      srTaskStatusMap: {},
      serviceReportList: [],
      currentReportSetting: {},
      srNewNoticeVisible: false,
      isActivated: true, // 组件是否被激活
      showReplaceProductCard: false,
      stepsActive: 0,
      stepData: [i18n.t('task.setting.taskTypeSetting.flow.tabs.title40'), i18n.t('task.setting.taskTypeSetting.flow.tabs.title41'), i18n.t('task.setting.taskTypeSetting.flow.tabs.title42')],
      // 质检字段
      intelligentFields: [],
      intelligentFieldsData: [],
      taskCheckFields: [],
      examplePictures: [],
      // 初始化工单/工单回执/回执金额的数据
      optionMaps: {
        task: [],
      },
      filterTypeList: ['text', 'textarea', 'number', 'select', 'user', 'date', 'phone', 'email', 'formula']

    }
  },
  watch: {
    srNewNoticeVisible(val) {
      if(!val) {
        localStorage.setItem('setting-sr-notice-close', '1')
      }
    },
    isUpdate: {
      immediate: true,
      handler(newValue, _) {
        if (newValue) {
          this.initData()
        }
      }
    },
  },
  computed: {
    optionsSelect() {
      let options = []
      this.showTips = false
      if(this.isShowPlanStartTime) options.push({value: 1, label: i18n.t('common.form.type.planStartTime')})
      if(this.isShowPlanEndTime) options.push({value: 2, label: i18n.t('common.form.type.planEndTime')})
      if(options.length <= 0 && this.isCalendar)  this.showTips = true
      return options
    },
    // 服务报告列表已存在的工单状态
   srListExistTypeStatus() {
     return this.serviceReportList.map(item => {
       return item.taskStatus
     })
   },
   // 确保提示只在当前页面显示
   srPopoverVisible: {
     get() {
       return this.srNewNoticeVisible && this.isActivated
     },
     set(v) {
       console.log(v, 'srPopoverVisible')
     }
   },
    waterMarkDirection() {
      return [
        {label : i18n.t('task.setting.taskTypeSetting.flow.tabs.topLeft'), value : 'topLeft'},
        {label : i18n.t('task.setting.taskTypeSetting.flow.tabs.bottomLeft'), value : 'bottomLeft'},
        {label : i18n.t('task.setting.taskTypeSetting.flow.tabs.topRight'), value : 'topRight'},
        {label : i18n.t('task.setting.taskTypeSetting.flow.tabs.bottomRight'), value : 'bottomRight'},
      ]
    },
    photoInfoArr() {
      return [
        {label : i18n.t('task.setting.taskTypeSetting.flow.tabs.operatorName'), value : 'name'},
        {label : i18n.t('task.setting.taskTypeSetting.flow.tabs.photoTime'), value : 'time'},
        {label : i18n.t('task.setting.taskTypeSetting.flow.tabs.photoPosition'), value : 'position'},
      ]
    },
    processArr() { 
      return [
        {label : i18n.t('common.base.start'), value : 'start'},
        {label : i18n.t('common.base.finish'), value : 'finish'}
      ]
    },
    taskProcessNodeArr() {
      return [
        {label : i18n.t('common.task.button.allot'), value : 'allot'},
        {label : i18n.t('common.task.button.start'), value : 'start'},
        {label : i18n.t('common.base.finish'), value : 'finish'},
        {label : i18n.t('common.task.button.balance'), value : 'cost'},
        {label : i18n.t('common.task.button.review'), value : 'returnVisit'},
        {label : i18n.t('common.base.close'), value : 'close'},
        {label : i18n.t('common.task.exceptionStatus.allot'), value : 'reallot'},
      ]
    },
    /* 是否为基础版 */
    isBasicEdition() {
      return isBasicEdition()
    },
    /* 是否为标准版 */
    isStandardEdition() {
      return isStandardEdition()
    },
    /* 是否为体验版 */
    isExperienceEdition() {
      return isExperienceEdition()
    },
    // 基础版功能隐藏服务报告
    isBasicEditionHideServiceReport() {
      return isBasicEditionHideServiceReport() 
    },
    // 基础版功能是否隐藏打印
    isBasicEditionHidePrintTask() {
      return isBasicEditionHidePrintTask() 
    },
    // 基础版功能是否隐藏支付
    isBasicEditionHidePay() {
      return isBasicEditionHidePay() 
    },
    taskIntelligentCheck() {
      const RootWindow = getRootWindow(window)
      return RootWindow.grayAuth?.taskIntelligentCheck || false
    },
    // 触发器灰度
    triggerGray(){
      const RootWindow = getRootWindow(window);
      return RootWindow.grayAuth?.TRIGGER || false;
    },
    isShowTaskServiceReport() {
      return this._isShowTaskServiceReport
    },
    newTriggerGray() {
      const RootWindow = getRootWindow(window);
      return RootWindow.grayAuth?.NEW_TRIGGER || false;
    },
  },
  methods: {
    async initData() {
      await this.getTypeData('task');
      await this.setDefaultFiledList()
    },

    setDefaultFiledList() {
      if (this.optionMaps['task'].length > 0) {
        this.setData(this.taskFlowData.taskTypeConfig.cancelApproveSetting)
        this.setData(this.taskFlowData.taskTypeConfig.pauseApproveSetting)
      }
    },


    setData(approveSetting) {

      if (approveSetting && approveSetting.conditions && approveSetting.conditions.length > 0) {
          this.setDefaultConditions(approveSetting.conditions)
      }
      if (approveSetting && approveSetting.level > 1) {
        // 二级审批存在
        if (approveSetting.multiApproverSetting && approveSetting.multiApproverSetting.length >0 && approveSetting.multiApproverSetting[0].conditions) {
          this.setDefaultConditions(approveSetting.multiApproverSetting[0].conditions)
        }
      }
    },

    setDefaultConditions(conditionsList) {
      conditionsList.forEach((item) => {
          item.forEach((ele)=> {
              this.$set(ele, 'fieldsOptions', this.optionMaps[ele.module]);
              if (ele.conditionItem.valueStr) {
                this.$set(ele.conditionItem, 'value', JSON.parse(ele.conditionItem.valueStr))
              }
              if (ele.conditionItem.fieldName) {
                this.optionMaps[ele.module].forEach((eleDetail)=> {
                  if (eleDetail.fieldName === ele.conditionItem.fieldName) {
                      this.$set(ele.conditionItem, 'field', eleDetail);
                  }
                })
              }
          })
        })
    },

    //高级设置只有 工单字段列表接口
    async getTypeData(tableName) {
      let params = {
        tableName: tableName,
        typeId: this.taskTypeId,
        isFromSetting: true,
        isShowRichText: false,
      }
      let allShowList = []
      await TaskApi.getAllFields(params).then(res=>{
        if (res) {
          res.forEach((item)=> {
            if (this.filterTypeList.includes(item.formType)) {
              allShowList.push(item)
            }
          })
          this.optionMaps[tableName] = allShowList;
        }
      })

    },


    // 获取工单状态的多语言名称
    getStateName(value) {
      let status = TaskStateEnum.getName(value)

      if(!status) {
        const node = this.srTaskStatusOptions?.find(item => item.optionName === value)
        if(node) status = node.displayName;
      }

      return status
    },
    getForeignName(name) {
      if (!name) return this.$t("task.serviceReport")
      const reg = /\{\{.+?}\}/
      if (reg.test(name)) return this.$t("task.serviceReport")
      return name
    },
    /** 获取是否开启备件替换产品附加组件灰度 */
    async getReplaceProductCard() {
      let res = await SettingApi.getReplaceProductCard();
      if(res.data === true){
        this.showReplaceProductCard = true
      }
    },
    // 获取生成服务报告的工单状态
    async getServiceReportTaskStatusOption() {
      const { success, data } = await SettingTaskApi.getServiceReportTaskStatusOption({
        taskTypeId: this.taskTypeId
      })
      this.srTaskStatusOptions = success ? data : []
      let mapObj = {}
      data.forEach(item => {
        mapObj[item.optionName] = item.displayName
      })
      this.srTaskStatusMap = mapObj
    },
    // 获取服务报告模板列表
    async getServiceReportList() {
      const { success, data } = await SettingTaskApi.getServiceReportListByTaskType({taskTypeId: this.taskTypeId})
      this.serviceReportList = success ? data : []
    },

    // 服务报告打开系统/个人模版设置弹窗
    srOpenTemplateDialog(type, setting) {
      this.currentReportSetting = setting || {}
      if(type === 'system') {
        this.openTemplateDialog('reportSetting')
      } else if(type === 'personal') {
        this.importPresonTemplate('reportSetting')
      }
    },

    // 服务报告保存系统模版设置
    reportSettingSave(reportSetting, params) {
      this.$refs.serviceReportEditDialogRef.updateSetting(reportSetting, params)
    },

    handleServiceReportSuccess() {
      this.$track.clickStat(this.$track.formatParams('SERVICE_REPORT_CREATE_RULE_SUCCESS'))
      this.getServiceReportList()
    },

    async getFieldType(id) {
      try {
        let res = await SettingApi.getFieldType({
          templateId: id
        })
        
        this.fieldTypeList = [
          ...(res.data?.cardInfoList || []).map(item => ({
            id: item.id,
            name: item.name,
            cardId: item.id
          })),
          ...(res.data?.fieldType || []).map(item => ({
            id: item.fieldName,
            name: item.displayName,
            displayName: item.displayName,
            fieldName: item.fieldName
          })),
          ...(res.data?.taskReceiptList || []).map(item => ({
            id: item.id,
            name: item.displayName,
            displayName: item.displayName,
            fieldName: item.fieldName
          })),
        ]
      } catch (error) {
        console.error(error);
      }
    },

    /** 获取工单表单、回执表单中必填的人员字段 */
    async fetchFromUser(id) {
      try {
        let res = await SettingApi.getFromUser(id);
        this.formList = res.data.list;
        this.receiptList = res.data.receiptList;

        this.buildApproveOptions();
      } catch (error) {
        console.error('fetch getFromUser => error', error);
      }
    },
    buildApproveOptions() {
      this.options.pause = this.approveOptions('pause');
      this.options.cancel = this.approveOptions('cancel');
    },
    /** 审批类型选项 */
    approveOptions(type) {
      let options = [
        {
          value: 'leader',
          label: this.$t('event.setting.serviceEventTypeSetting.flow.component.settingFlowSpecific.label2'),
        },
        {
          value: 'users',
          label: this.$t('event.setting.serviceEventTypeSetting.flow.component.settingFlowSpecific.label3'),
        },
        {
          value: 'createUser',
          label: this.$t('task.setting.taskTypeSetting.flow.components.taskCreator'),
        },
        {
          value: 'userAdmin',
          label: this.$t('event.setting.serviceEventTypeSetting.flow.component.settingFlowSpecific.label5'),
        },
        {
          value: 'promoter',
          label: this.$t('event.setting.serviceEventTypeSetting.flow.component.settingFlowSpecific.label6'),
        },
      ];

      options = [
        ...options,
        ...this.formList.map((item) => {
          return {
            label: `${this.$t('task.setting.taskTypeSetting.flow.components.formUser')}:${ item.showName}`,
            value: item.stateTemplateId,
          };
        }),
      ];

      if (type === 'cancel') {
        options = [
          ...options,
          ...this.receiptList.map((item) => {
            return {
              label: `${this.$t('task.setting.taskTypeSetting.flow.components.reviewFormUser')}:${ item.showName}`,
              value: item.stateTemplateId,
            };
          }),
        ];
      }

      return options;
    },
    /** 格式化审批人员名称 */
    getApproverNames(approvers) {
      return approvers.map((item) => item.displayName).join(',');
    },
    getApproverIds(approvers) {
      return approvers.map((item) => item.staffId);
    },
    /** 选择指定审批人员 */
    selectApproveUser(type) {
      let selected = [];

      if (type === 'planRemind') selected = this.taskFlowData.taskTypeConfig.noticeUsers;

      let options = {
        title: ['overTime', 'planRemind'].includes(type) ? this.$t('task.setting.taskTypeSetting.flow.components.tip3') : this.$t('task.setting.taskTypeSetting.flow.components.tip4'), // [选填] 默认值为 '请选择人员'
        max: 14, // [选填]最大人数：当值小于等于0或者不填时，不对选择人数做限制，max值为1时单选，大于1时多选
        selectedUsers: selected, // [选填] 已选人员 每个人员必须包括userId,displayName,staffId,head这四个属性，只有带max大于1时生效
        mode: BaseSelectUserModeEnum.Filter
      };

      this.$fast.select.multi.user(options)
        .then((res) => {
          if (res.status != 0) return;
          switch (type) {
          case 'planRemind': // 计划提醒指定人员
            this.taskFlowData.taskTypeConfig.noticeUsers = res.data.users;
            break;
          default:
            break;
          }
        })
        .catch((err) => {
          console.warn(err);
        });
    },
    /** 更新审批设置 */
    changeApproveSetting(setting, key) {
      switch (key) {
      case 'pause':
        this.$set(this.taskFlowData.taskTypeConfig, 'pauseApproveSetting', setting);
        break;
      case 'cancel':
        this.$set(this.taskFlowData.taskTypeConfig, 'cancelApproveSetting', setting);
        break;
      default:
        break;
      }
    },
    /**
     * 个人模板设置弹窗
     */
    importPresonTemplate(type) {
      this.templateType = type;
      this.isShowTemplateUploadModal = true;
    },

    /**
     * @description: 服务报告 新建、编辑、删除
     * @param {String} type create/edit/delete
     * @param {Object} item
     */    
    serviceReportClickHandler(type, item) {
      if(type === 'create') {
        this.$track.clickStat(this.$track.formatParams('SERVICE_REPORT_CREATE_RULE'))
      }
      if(type === 'create' || type === 'edit') {
        this.$refs.serviceReportEditDialogRef.openDialog(type, item)
      } else if(type === 'delete') {
        
      this.$confirm(this.$t('common.base.tip.areYouWantDeleteIt', {data1: this.getForeignName(item.foreignName)}), this.$t('common.base.toast'), {
        confirmButtonText: this.$t('common.base.makeSure'),
        cancelButtonText: this.$t('common.base.cancel'),
        type: 'warning'
      }).then(()=>{
        SettingTaskApi.removeServiceReportTemplate({id: item.id})
          .then(res => {
            if(res.success) {
              this.$message.success(this.$t('common.base.deleteSuccess'))
              this.getServiceReportList()
            } else {
              this.$message.error(res.message || this.$t('common.base.tip.operationFail'))
            }
          })
      }).catch(()=>{})
      }
    },

    // 打开新服务报告功能介绍弹窗
    openServiceReportIntroDialog() {
      this.$track.clickStat(this.$track.formatParams('SERVICE_REPORT_LEARN_MORE'))

      this.$refs.functionIntroDialogRef.openDialog()
    },
    /**
     * 系统模板设置弹窗
     */
    openTemplateDialog(type) {
      this.templateType = type;
      this.isShowSystemModal = true;
    },
    /**
     * 将对象转化成接口参数格式
     */
    objectToParams(obj, valueKey) {
      return Object.keys(obj).map(key => {
        return {
          name: key,
          [valueKey]: Array.isArray(obj[key]) ? obj[key].join(',') : obj[key]
        }
      });
    },
    /** 保存公共设置 */
    async saveCommonSetting(otherParams) {
      let params = convertDataToParams(this.taskFlowData.taskTypeConfig);
      params = {
        ...params,
        ...otherParams
      };

      return await SettingApi.saveProcess(params);
    },
    /**
     * 保存回执设置
     */
    async saveOptionSetting(otherParams) {
      let {taskTypeId, taskTypeConfig} = this.taskFlowData;
      let saveOptionFormList = this.objectToParams(taskTypeConfig.options, 'state');

      // 工单流程完成时间取审批完成时间-参数数据处理
      const { changeCompleteFlag, changeCompleteNode } = this.taskFlowData?.taskTypeConfig?.config;
      taskTypeConfig.config.positionExceptionConfig.changeCompleteFlag = changeCompleteFlag || false;
      taskTypeConfig.config.positionExceptionConfig.changeCompleteNode = changeCompleteNode || [];

      let typeConfigForms = this.objectToParams(taskTypeConfig.config.positionExceptionConfig, 'value');

      // return 
      let wikiSetting = this.fieldTypeList.filter(v => this.wikiSettingIds.includes(v.id))

      let params = {
        templateId: taskTypeId,
        wikiSetting,
        saveOptionFormList,
        typeConfigForms,
        ...otherParams
      }

      return await SettingApi.advancedSetting(params);
    },
    /**
     * 保存 (暴露的方法)
     */
    async submit(otherParams) {
      let that = this;

      // 开启智能质检灰度
      if(this.taskIntelligentCheck) {
        // 开启智能质检
        if(that.intelligenceData.pictureCheckSwitch){
          this.$emit('intelligence', true)
          if(
            that.intelligenceData?.examplePictures?.length < 1
            || !that.intelligenceData?.minPictureCheckScore
            || (!that.intelligenceData?.minTaskCheckScore && !that.intelligenceData?.minTaskCheckCount)
            || that.intelligenceData.taskCheckFields?.length < 1
          ){
            this.$emit('intelligence', false)
            return that.$platform.notification({
              type: 'error',
              message: this.$t('task.setting.taskTypeSetting.flow.tabs.tip7'),
            });
          }
        }
        await this.getIntelligentConfigSave()
      }
      
      return new Promise((resolve, reject) => {
        try {
          this.saveCommonSetting(otherParams).then(res => {
            if(res.status === 0) {
              that.saveOptionSetting(otherParams).then(res2 => {
                if(res2.status === 0) {
                  this.$platform.notification({
                    title: this.$t('common.base.saveSuccess'),
                    type: 'success'
                  });
                  this.$customerOperateLog(logDataToParams('other', this.taskFlowData)); // 记录用户操作日志
                  resolve();
                }
              });
            }else {
              this.$platform.notification({
                title: res.message,
                type: 'error'
              });
              reject();
            }

          })
          
        } catch (error) {
          reject(error);
        }
      });
    },
    /** 检查内容是否有修改 (暴露的方法) */
    checkModified() {
      let {taskTypeConfig, initTaskTypeConfig} = this.taskFlowData;
      const formCheck = JSON.stringify(taskTypeConfig) != JSON.stringify(initTaskTypeConfig);
      return formCheck;
    },
    /** 同步初始数据 (暴露的方法) */
    resetInit() {
      this.taskFlowData.taskTypeConfig = _.cloneDeep(this.taskFlowData.initTaskTypeConfig);
    },
    /** 质检高级设置 */
    getStepsActive(index) {
      this.stepsActive = index
    },
    /** 质检高级设置 上一步*/
    intelligentPre() {
      if(this.stepsActive > 0) return -- this.stepsActive
    },
    /** 质检高级设置 下一步*/
    intelligentNext() {
      if(this.stepsActive < 2) return ++ this.stepsActive
    },
    intelligenceFileUpload(file) {
      this.$set(this.intelligenceData, 'examplePictures', file)
    },
    inputIntelligentFields(value) {
      if(!value) return
      if(!this.intelligentFieldsData.length) {
        this.$nextTick(() => {
          // 实在是没办法了 对不起 T T
          const elCascaderMenu = document.querySelector('.el-cascader-menu')
          elCascaderMenu.innerHTML = `<div class="el-cascader-menu__empty-text">${this.$t('common.base.tip.noData')}</div>`
        })
      }
    },
    updateIntelligentFields(value) {
      try {
        this.taskCheckFields = value
        if(this.taskCheckFields[0]) {
          this.intelligenceData.taskCheckFields = []
          this.intelligenceData.taskCheckFields.push({
            [this.taskCheckFields[0]]: this.taskCheckFields[1]
          })
        }
      } catch (error) {
        console.error(error);
      }
    },
    // 查询智能质检字段
    getIntelligentFieldsData() {
      SettingTaskApi.aiQualityCheckFields({taskTypeId: this.taskTypeId})
        .then(res => {
          if(res.success) {
            const result = res.result || {}
            const fields = []
            for (let key in result) {
              result[key] = result[key].map(item => {
                return {
                  ...item,
                  value: item.id,
                  label: item.displayName,
                }
              })
              fields.push({
                value: key,
                label: key === 'task' ? this.$t('task.setting.taskFieldsSetting.taskForm') : this.$t('task.setting.taskTypeSetting.flow.tabs.receiptForm'),
                children: result[key]
              })
            }
            this.intelligentFieldsData = fields
          }
        }).catch(error => {
          console.warn(error);
        })
    },
    // 保存智能质检的配置
    async getIntelligentConfigSave() {
      const params = this.buildIntelligentConfigSaveParams()
      await SettingTaskApi.getIntelligentConfigSaveApi(params).then(res => {
        if(!res.success) {
          return this.$platform.notification({
            type: 'error',
            message: res.message 
          });   
        }
      }).catch(error => {
        console.error(error)
      })
    },
    buildIntelligentConfigSaveParams() {
      let intelligenceData = _.cloneDeep(this.intelligenceData);
      intelligenceData.taskTypeId = this.taskTypeId
      if(!intelligenceData.minPictureCheckScore) intelligenceData.minPictureCheckScore = null
      if(!intelligenceData.minTaskCheckCount) intelligenceData.minTaskCheckCount = null
      if(!intelligenceData.minTaskCheckScore) intelligenceData.minTaskCheckScore = null
      intelligenceData.examplePictures = intelligenceData.examplePictures.map(item => {
        return {
          type: 'TASK_TYPE',
          typeId: this.taskTypeId,
          ossUrl: item.url ?? '',
          fileId: item.id ?? '',
          fileName: item.filename,
          picId: item.picId
        }
      })
      return intelligenceData
    },
    getDefaultTaskCheckFields() {
      try {

        if(this.intelligenceData?.taskCheckFields?.length > 0) {
          let taskCheckFields = this.intelligenceData?.taskCheckFields[0] ?? {}
          let fields = []
          for(let key in taskCheckFields) {
            fields.push(key, taskCheckFields[key])
          }
          this.taskCheckFields = fields
        }
        
      } catch(error) {
        console.error(error);
      }
    },
  },

  async activated() {
    this.isActivated = true
    // 判断是否打开服务报告 新功能提示
    this.srNewNoticeVisible = !Boolean(localStorage.getItem('setting-sr-notice-close'))
    if(this.taskTypeId) {

      if(this.taskIntelligentCheck) {
        // 智能质检
        this.getIntelligentFieldsData()
        this.getDefaultTaskCheckFields()
      }

      this.fetchFromUser(this.taskTypeId);
      this.getReplaceProductCard(this.taskTypeId);
      this.getFieldType(this.taskTypeId)
      await this.getServiceReportTaskStatusOption()
      this.getServiceReportList()

    }
  },
  deactivated() {
    this.isActivated = false
  },
  components: {
    [ApproveSetting.name]: ApproveSetting,
    [SystemTemplateDialog.name]: SystemTemplateDialog,
    [TemplateUploadDialog.name]: TemplateUploadDialog,
    [FunctionIntroDialog.name]: FunctionIntroDialog,
    [ServiceReportEditDialog.name]: ServiceReportEditDialog,
    [TriggerListSetting.name]: TriggerListSetting
  }
}
</script>

<style lang="scss" scoped>
.other-setting-panel{
    width: 100%;
    min-height: calc(100vh - 48px);
    padding: 12px;
    .other-setting-main{
        height: 100%;
        background: #FFFFFF;
        border-radius: 4px;
        padding: 20px 20px;
        & > div {
          position: relative;
          padding-left: 8px;
          font-size: 14px;
          color: #999999;
          h2{
            color: #333333;
            font-size: 14px;
            margin: 36px 0 8px 0;
            span{
              font-size: 12px;
              font-weight: 400;
              color: #999999;
            }
          }
          p{
              margin-bottom: 8px;
              color: #666666;
          }
          &::before{
            content: "";
            position: absolute;
            left: 0;
            top: 2px;
            display: inline-block;
            width: 2px;
            height: 15px;
            background: $color-primary-light-6;
            border-radius: 2px;
          }
        }
        & > div:not(:last-child)::after{
          content: "";
          position: relative;
          top: 16px;
          display: block;
          width: 100%;
          border-top: 1px dashed #D9D9D9;
        }
        .show-tips {
          color: #FAAD14;
          margin-top: 10px;
        }
    }
}

::v-deep .setting-approve-people{
  display: flex;
  align-items: center;
  margin-bottom: 0 !important;
}
// 智能质检
.setting-intelligent{
  // 修改上传按钮样式
  .base-upload{
    ::v-deep .base-upload-btn{
      padding: 6px 15px;
    }
  }
  
  .setting-intelligent-rule{
    h2{
      margin-top: 24px !important;
    }
    .intelligent-main{
      padding: 16px 24px;
      background-color: #FAFAFA;
      .intelligent-steps {
        margin-bottom: 20px;
      }
      .intelligent-content{
        min-height: 148px;
        margin: 20px 0;
      }
      .w240{
        width: 240px;
      }
    }
  }
}

.w-104{
  width: 104px;
}

.w-120{
    width: 120px;
}
.w-542{
    width: 542px;
}
.w-678{
  width: 678px;
}

.mt-12{
    margin-top: 12px;
}
.mb-12{
    margin-bottom: 12px;
}
.mr-50{
    margin-right: 50px;
}
.ml-16{
    margin-left: 16px;
}
.mt-8{
    margin-top: 8px;
}

/** element-ui */
.el-checkbox{
    margin-bottom: 0;
}
.el-button--small{
    height: 28px;
    padding: 6px 15px;
}
.el-button.is-plain:hover {
  border-color: #ebeef5 !important;
  color: #c0c4cc !important;
}
.el-switch{
  float: right;
}

.el-icon-question {
  vertical-align: middle;
  color: #666;
  font-size: 16px;
}

.setting-service-report {
  .setting-service-report-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    &__right {
      display: flex;
      align-items: center;
    }
    .desc {
      color: #262626;
      font-size: 12px;

      ::v-deep .el-button--text {
        font-size: 12px;
        padding: 0;
        height: auto;
      }
    }
  }
  .service-report-item {
    display: flex;
    justify-content: space-between;
    margin-bottom: 12px;
    border: 1px solid #D9D9D9;
    border-radius: 4px;
    color: #595959;
    &__left {
      display: flex;
      align-items: center;
      justify-content: center;
      background: #E8E8E8;
      width: 120px;
      padding: 8px;
    }
    &__right {
      display: flex;
      flex: 1;
      justify-content: space-between;
      align-items: center;
      padding: 24px;
      ::v-deep .red span {
        color: #D9363E;
      }
    }
    .service-report-item-content {
      span {
        color: #262626;
      }
    }
    &:hover {
      border-color: $color-primary-light-6;
    }
  }
}

.sr-popover {
  .sr-popover-content {
    text-align: left;
    color: #171A1D;
    h3 {
      word-break: break-word;
    }
    span {
      font-size: 12px;
      color: rgba(23, 26, 29, 0.6);
    }

    .el-button {
      margin-top: 12px;
      width: 100%;
    }

    .el-icon-close {
      font-size: 14px;
      position: absolute;
      right: 10px;
      top: 10px;
      cursor: pointer;
    }
  }
}
</style>
<style lang="scss" scoped>
// 企微端样式
@import '@src/modules/setting/openData.scss';
</style>